package net.m510.autosurfer.idemitsu;

import java.net.URI;
import java.util.logging.Logger;

import net.m510.autosurfer.common.DocumentGetProcess;
import net.m510.autosurfer.common.exception.InvalidDocumentException;

import org.apache.http.HttpHost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class IdemitsuLogout extends DocumentGetProcess {
	private static final Logger log = Logger.getLogger(IdemitsuLogout.class.getName());

	public IdemitsuLogout() {
		this(null,null);
	}
	
	public IdemitsuLogout(CloseableHttpClient client,HttpClientContext context) {
		super(client, context);
		super.log = log;
	}

	@Override
	protected URI getUri(Document doc) {
		// ログアウトタグからログアウト用URLを取り出す
		final String LOGOUT_ID="ログアウト";
		Elements e = doc.getElementsByAttributeValue("alt",LOGOUT_ID);
		if ( e.isEmpty() ) throw new InvalidDocumentException("alt "+LOGOUT_ID+"が見つかりません",doc);
		Element a = e.first().parent();
		log.fine("logout a src="+a.outerHtml());
		if ( !a.tag().getName().equals("a") ) throw new InvalidDocumentException("ログアウト用のaタグが見つかりません",doc);
		String anchor = a.attr("href");
		HttpHost host = context.getTargetHost();
		URI uri = URI.create(host.toURI());
		uri = uri.resolve(anchor);
		return uri;
	}
}
